<template>
  <a-card :bordered="false">
    <search :config="searchConfig" @search="search" @getHeight="getHeight"/>
    <div class="page_table">
      <vxe-grid
        ref="xGrid"
        :border="true"
        :resizable="true"
        :showOverflow="true"
        size="mini"
        :loading="loading"
        :height="pageHeight-seachHeight-94"
        :align="left"
        :columns="columns"
        :data="dataSource"
        :toolbar-config="tableToolbar"
        :checkbox-config="checkboxConfig"
        v-bind="vexConfig"
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectChangeEvent"
      >
        <template #toolbar_buttons>
          <div class="table-operator">
            <a-button v-has="'customRelation:add'" @click="handleAdd">新增</a-button>
            <a-button v-has="'customRelation:delete'" @click="batchDel">删除</a-button>
            <a-button v-has="'customRelation:synchronization'" @click="handleSync()">同步</a-button>
            <a-button v-has="'customRelation:export'" @click="downExportXls('client_relations')">导出</a-button>
          </div>
        </template>
        <template #custCode="{ row,rowIndex }">
          <a @click="handleDetail(row)">{{ row.custCode }}</a>
        </template>
        <template #isAuth="{ row }">
          {{ row.isAuth == 1 ? '是' : '否' }}
        </template>
        <template #action="{ row,rowIndex }">
          <a v-has="'customRelation:update'" @click="handleEdit(row)">编辑</a>
          <a-divider type="vertical"/>
          <a v-has="'business:log'" href='javascript:' @click='handleBusiness("客户关系",row)'>日志</a>
        </template>
        <template #update="{ row }">
          <a-switch :checked="row.status" size="small" @change="handleStatus(row,$event)"/>
        </template>
        <template #businessType="{ row,rowIndex }">
          {{ row.businessType == 1 ? '业务订单' : '企业订单' }}
        </template>
        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync="ipagination.current"
            :page-size.sync="ipagination.pageSize"
            :total="ipagination.total"
            :pageSizes="ipagination.pageSizeOptions"
            @page-change="handlePageChange">
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>

    <business-log ref="businessLog"></business-log>

    <relationModel ref="modalForm" @ok="modalFormOk"></relationModel>
  </a-card>
</template>

<script>
import relationModel from '../terminal/modules/relationModel.vue'
import { PageListMixin } from '@/mixins/PageListMixin'
import { getAction, postAction } from '@api/manage'
import Vue from 'vue'

export default {
  name: 'userorgerl',
  mixins: [PageListMixin],
  components: {
    relationModel
  },
  data() {
    return {
      selectedRowKeys: [],
      description: '客户关系',
      searchConfig: [
        {
          type: 'input',
          name: 'custCode',
          placeholder: '客户编号'
        },
        {
          type: 'input',
          name: 'custName',
          placeholder: '客户名称'
        },
        {
          type: 'input',
          name: 'userCode',
          placeholder: '用户账号'
        },
        {
          type: 'a-select',
          name: 'status',
          placeholder: '请选择状态',
          option: [
            {
              name: '启用',
              value: 1
            },
            {
              name: '停用',
              value: 0
            }]
        },
        {
          type: 'input',
          name: 'userName',
          placeholder: '用户名称'
        },
        {
          type: 'tree-select',
          name: 'custOrgCode',
          dataType: 'org',
          showSearch:true,
          placeholder: '请选择客户组织'
        },
        {
          type: 'tree-select',
          name: 'userOrgCode',
          dataType: 'org',
          showSearch:true,
          placeholder: '请选择用户组织'
        },
      ],
      //表头
      columns: [],
      //列设置
      settingColumns: [],
      defColumns: [
        { type: 'checkbox', width: 60, fixed: 'left' },
        {
          fixed: 'left',
          title: '客户编号',
          field: 'custCode',
          minWidth: 80,
          slots: { default: 'custCode' }
        },
        {
          title: '客户名称',
          minWidth: 80,
          field: 'custName'
        },
        {
          title: '客户所属组织编号',
          field: 'custOrgCode',
          minWidth: 120,
        },
        {
          title: '客户所属组织名称',
          minWidth: 120,
          field: 'custOrgName'
        },
        {
          title: '是否授权',
          minWidth: 80,
          field: 'isAuth',
          slots: { default: 'isAuth' }
        },
        {
          title: '用户账号',
          minWidth: 80,
          field: 'userCode'
        },
        {
          title: '用户名称',
          minWidth: 80,
          field: 'userName'
        },
        {
          title: '用户所属组织编号',
          field: 'userOrgCode',
          minWidth: 120,
        },
        {
          title: '用户所属组织名称',
          minWidth: 120,
          field: 'userOrgName'
        },
        {
          title: '备注',
          minWidth: 80,
          field: 'remarks'
        },
        {
          title: '创建人',
          minWidth: 80,
          field: 'createName'
        },
        {
          title: '创建时间',
          minWidth: 80,
          field: 'createTime'
        },
        {
          title: '更新人',
          minWidth: 80,
          field: 'updateName'
        },
        {
          title: '更新时间',
          minWidth: 80,
          field: 'updateTime'
        },
        {
          title: '状态',
          field: 'status',
          width: 60,
          fixed: 'right',
          minWidth: 80,
          slots: { default: 'update' }
        },
        {
          fixed: 'right',
          title: '操作',
          minWidth: 120,
          slots: { default: 'action' }
        }
      ],
      isorter: {
        permflag: 'customer_relation_page_impl'
      },
      url: {
        list: window._CONFIG['domianURL'] + '/customer/cnCustomerRelation/findPageList',
        // detail: window._CONFIG['domianURL'] + '/userorgrelation/cnUserOrgRelation/saveOrUpdate',
        edit: window._CONFIG['domianURL'] + '/mdsProduct/saveOrUpdateEntity',
        deleteBatch: '/customer/cnCustomerRelation/deleteBatch',
        delete: window._CONFIG['domianURL'] + '/userorgrelation/cnUserOrgRelation/delete',
        startOrStopUrl: window._CONFIG['domianURL'] + '/customer/cnCustomerRelation/updateStatus',
        exportXlsUrl: window._CONFIG['domianTpmURL'] + 'budget/tpmBudgetFee/exportXls',
        sync: window._CONFIG['domianURL'] + '/customer/cnCustomerRelation/waiQinQuery'
      }
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  created() {
    this.initColumns()
    console.log('数据字典', initDictOptions('business_type'))
  },
  mounted() {
    // initDictOptions('org_type').then(res => {
    //   if(res.success) {
    //     res.result.forEach(item => {
    //       if(!dictData.orgTypes.hasOwnProperty(item.dictDataDesc)){
    //         Object.defineProperty(dictData.orgTypes, item.dictDataDesc, {
    //           value: item.dictDataDesc,
    //           writable: true
    //         });
    //       }
    //     })
    //   }
    // })

  },
  methods: {
    //列表设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.field == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.field)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    changeStatus(e, item) {
      if (e) {
        this.startorstopByid(1, item.id)
      } else {
        this.startorstopByid(0, item.id)
      }
    },
    startorstopByid(status, id) {
      let that = this
      this.$confirm({
        title: '确认修改',
        content: '是否' + (status == 0 ? '停用' : '启动') + '选中数据？',
        onOk() {
          that.loading = true
          getAction(that.url.startOrStopUrl, { ids: id, status: status }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
              that.onClearSelected()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.loading = false
          })
        },
        onCancel() {
          // that.loadData();
          // that.onClearSelected();
        },
      })
    },
    handleView: async function (row) {
      this.$refs.modalForm.edit(row)
      this.$refs.modalForm.title = '查看自定义产品组'
      this.$refs.modalForm.disableSubmit = true
    },
    handleEdit: async function (row) {

      this.$refs.modalForm.edit(row)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.field)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.field == 'action') {
            return true
          }
          if (colSettings.includes(item.field)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
